import datetime
import json

from django.db import IntegrityError
from django.http.response import HttpResponse
from student.models import Student
from django.core import serializers


# Create your views here.

def login(request):
    if request.method == "GET":
        return
    data = json.loads(request.body)
    if not data.get("id"):
        return HttpResponse("请输入编号")
    if not data.get("password"):
        return HttpResponse("请输入密码")
    try:
        user = Student.objects.filter(student_number=data.get("id"), student_password=data.get("password"))
        if not user:
            return HttpResponse('用户名或密码错误')
        return HttpResponse(json.loads(serializers.serialize("json", user)))
    except BaseException as e:
        print(e)
        return HttpResponse("查询错误")


def register(request):
    if request.method == "GET":
        return

    data = json.loads(request.body)
    if not data.get("id"):
        return HttpResponse("请输入学号")
    if not data.get("name"):
        return HttpResponse("请输入姓名")
    if not data.get("sex"):
        return HttpResponse("请输入性别")
    if not data.get("telephone"):
        return HttpResponse("请输入电话")
    if not data.get("password"):
        return HttpResponse("请输入密码")
    if not data.get("birthday"):
        return HttpResponse("请输入生日")
    if not data.get("department"):
        return HttpResponse("请输入院系")
    if not data.get("class"):
        return HttpResponse("请输入班级")
    try:
        # 生日格式为  yy-MM-dd
        birthday = datetime.datetime.strptime(
            data.get("birthday"), "%Y-%m-%d"
        )
        student_person = Student.objects.create(
            student_number=data.get("id"),
            student_name=data.get("name"),
            student_sex=data.get("sex"),
            student_phone=data.get("telephone"),
            student_password=data.get("password"),
            student_birthday=birthday,
            student_class=data.get("class"),
            student_department=data.get("department")
        )
        student_person.save()
        return HttpResponse("注册成功")
    except IntegrityError as i:
        print(i)
        return HttpResponse("账户已注册")
    except BaseException as e:
        print(e)
        return HttpResponse("注册失败")


class StudentInfo:
    def __init__(self, id, name, birthday, sex, department, schoolClass, telephone, password):
        self.id = id
        self.name = name
        self.birthday = birthday
        self.sex = sex
        self.department = department
        self.schoolClass = schoolClass
        self.telephone = telephone
        self.password = password

    def __str__(self):
        return str({
            "id": self.id,
            "name": self.name,
            "birthday": str(self.birthday.year) + '-' + str(self.birthday.month) + '-' + str(self.birthday.day),
            "sex": self.sex,
            "department": self.department,
            "class": self.schoolClass,
            "telephone": self.telephone,
            "password": self.password
        })


def getStudents(request):
    """
    获取所有学生信息

    :param request:
    :return: 所有学生信息的数组
    """
    students = []
    all_students = Student.objects.all()
    for i in all_students:
        s = str(
            StudentInfo(i.pk, i.student_name, i.student_birthday, i.student_sex, i.student_department, i.student_class,
                        i.student_phone, i.student_password))
        students.append(s)
    return HttpResponse(json.dumps(students))


def get_student(stu_id):
    """
    获取单个学生信息

    :param stu_id: 要获取信息的学生的id
    :return: 所有学生信息的数组
    """
    student = Student.objects.filter(student_number=stu_id)[0]
    s = str(StudentInfo(student.pk, student.student_name, student.student_birthday, student.student_sex,
                        student.student_department, student.student_class,
                        student.student_phone, student.student_password))
    return s


def deleteStudent(request):
    """
    删除学生

    :param request: request必须为POST，参数必须包含要删除的学生的id
    :return: 删除状态
    """
    if request.method == "GET":
        return
    data = json.loads(request.body)
    if not data.get("id"):
        return HttpResponse("请输入学生编号")
    try:
        s = Student.objects.get(student_number=data.get("id"))
        s.delete()
        return HttpResponse("删除成功")
    except BaseException as e:
        print(e)
        return HttpResponse("删除失败")


def changeStudent(request):
    if request.method == "GET":
        return
    data = json.loads(request.body)
    try:
        birthday = datetime.datetime.strptime(
            data.get("birthday"), "%Y-%m-%d"
        )
        student = Student.objects.filter(student_number=data.get("id"))
        student.update(
            student_name=data.get("name"),
            student_sex=data.get("sex"),
            student_phone=data.get("telephone"),
            student_birthday=birthday,
            student_department=data.get("department"),
            student_class=data.get("class")
        )
        return HttpResponse("修改成功")
    except BaseException as e:
        print(e)
        return HttpResponse("修改失败")

def changePassword(request):
    if request.method == "GET":
        return
    data = json.loads(request.body)
    if not data.get("newPsd"):
        return HttpResponse("请输入编号")
    if not data.get("oldPsd"):
        return HttpResponse("请输入旧密码")
    if not data.get("newPsd"):
        return HttpResponse("请输入新密码")

    try:
        user = Student.objects.filter(student_number=data.get("id"), student_password=data.get("oldPsd"))
        user.update(student_password=data.get("newPsd"))
        return HttpResponse("修改成功")
    except BaseException as e:
        print(e)
        return HttpResponse("修改失败")
